package cn.fzhui.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.QueryRunner;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库工具类
 */
public class DBUtils {

    private static DataSource dataSource;


    static {
        Properties properties = new Properties();

        // 获取输入流
        InputStream inputStream = DBUtils.class.getClassLoader().getResourceAsStream("druid.properties");

        try {
            // 加载配置
            properties.load(inputStream);

            // 获取数据源
            dataSource = DruidDataSourceFactory.createDataSource(properties);

        } catch (Exception exception) {
            exception.printStackTrace();
        }

    }

    /**
     * 获取数据库连接
     *
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 获取QueryRunner
     *
     * @return
     */
    public static QueryRunner getQueryRunner() {
        return new QueryRunner(dataSource);
    }

}
